#Gopher文件访问协议
#   实现从主机上请求相关文档浏览的功能
#

import socket

def getCfg():
    file = open('./cfg', 'r')
    lines = file.readlines()
    host = lines[0].strip('host=').strip('\n')
    port = lines[1].strip('port=').strip('\n')
    file.close()
    return (host, int(port))

sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print('please input local host/port:')

cfg = getCfg()
print(cfg)

host = cfg[0]
port = cfg[1]

sockfd.bind((host, port))
sockfd.listen(5)

try:
    while True:
        (sockAcc, addr) = sockfd.accept()
        if sockAcc:
            data = sockAcc.recv(1024)
            file = open(data.decode('utf-8'), 'r')
            while True:
                ret = file.read(1024)
                if not ret:
                    sockAcc.send("".encode())
                    break
                sockAcc.send(ret.encode())
            file.close()
            sockAcc.close()
except:
    sockfd.close()